package com.daocao.hua.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.daocao.hua.R;
import com.daocao.hua.api.Api;
import com.daocao.hua.api.bean.PaymentNoticeCancelBean;
import com.daocao.hua.api.callback.ShenheContract;
import com.daocao.hua.api.requestInfo.ShenheRequest;
import com.daocao.hua.constant.Const;
import com.daocao.hua.event.OnHomeEventMsg;
import com.daocao.hua.model.ConfirmDilaogModel;
import com.daocao.hua.model.RepayStatusDialogModel;
import com.daocao.hua.model.RestartPayModel;
import com.daocao.hua.util.Network;
import com.daocao.hua.util.RxLifeUtil;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.UI;
import com.daocao.hua.util.Util;
import com.daocao.hua.view.CircularProgress;
import com.daocao.hua.view.Dialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 2017/8/29.
 */

public class ShenHeActivity extends BaseActivity implements ShenheContract.View {
    @BindView(R.id.txt_tips)
    TextView txtTips;
    @BindView(R.id.progressBar)
    CircularProgress progressBar;
    @BindView(R.id.btn_repay)
    SuperButton btnRepay;
    private Unbinder unbiner;
    private ShenheRequest api;
    private RestartPayModel data;
    private String dealId;
    private String mMoney;
    private String overdue;
    private float balance;
    private int totalMoney;
    private ArrayList<String> explain;
    private WebView mWebView;
    private boolean isRecharge;
    private String order;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shenheactivity);
        unbiner = ButterKnife.bind(this);
        initSecBar();
        init();
    }

    private void init() {
        mWebView = new WebView(getApplicationContext());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient());
//        String tips = getResources().getString(R.string.shenhe_tips);
//        txtTips.setText(tips + PreferenceUtils.getString(this, Const.KEY.SERVICE_PHONE, "") + "。");
        api = ShenheRequest.create();
        api.attachView(this);

        Intent dataIntent = getIntent();
        dealId = dataIntent.getStringExtra("deal_id");
        mMoney = dataIntent.getStringExtra("money");
        overdue = dataIntent.getStringExtra("overdue");
        balance = dataIntent.getFloatExtra("balance", 0f);
        totalMoney = dataIntent.getIntExtra("total_money", 0);
        explain = dataIntent.getStringArrayListExtra("explain");
        order = dataIntent.getStringExtra("order");
        isRecharge = dataIntent.getBooleanExtra("isRecharge", false);
        if (isRecharge) {
            btnRepay.setVisibility(View.GONE);
        }

        if (explain != null && explain.size() != 0) {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < explain.size(); i++) {
                builder.append(explain.get(i) + "\n");
            }
            txtTips.setText(builder);
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.onPause();
            mWebView.destroy();
            mWebView = null;
        }
        api.detachView();
        api = null;
        unbiner.unbind();
    }

    @Override
    public void showError() {

    }

    private boolean isGotoPay = false;

    @Override
    protected void onResume() {
        super.onResume();
        if (isGotoPay) {
            isGotoPay = false;
            api.getRepayDialog();
        }
    }

    @Override
    public void complete() {
        showLoading(false);
    }

    @Override
    public void onRequestStart() {
        showLoading(true);
    }

    private void showLoading(boolean b) {
        if (progressBar != null) {
            if (b)
                progressBar.setVisibility(View.VISIBLE);
            else
                progressBar.setVisibility(View.GONE);
        }
    }

    @Override
    public void getRestartPaySuccess(RestartPayModel item) {
        data = item;
//        "new_order": 1   //是否需要重新生成订单：0 - 否， 1 - 是

        if (data.data.new_order == 0) {
            if (data.data.go_alipay == 1) {
                isGotoPay = true;
                if (!checkAliPayInstalled(this)) {
                    mWebView.loadUrl(data.data.alipay_money_links);
                    return;
                }
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(Const.ALIPAY_START + data.data.alipay_money_links + Const.ALIPAY_END);
                intent.setData(content_url);
                startActivity(intent);
            } else if (data.data.go_alipay == 0) {
                mWebView.loadUrl(data.data.alipay_money_links);
            }
        } else if (data.data.new_order == 1) {
            Intent intent = new Intent(this, V3RepayMoneyActivity.class);
            intent.putExtra("deal_id", dealId);
            intent.putExtra("money", mMoney);
            intent.putExtra("overdue", overdue);
            intent.putExtra("total_money", totalMoney);
            intent.putExtra("balance", balance);
            startActivity(intent);
            overridePendingTransition(R.anim.right_enter, R.anim.left_out);
            finish();
        }
    }

    @Override
    public void getRepayDialogSuccess(RepayStatusDialogModel item) {
        //订单状态：0 - 待确认、 1 - 失败、 2 - 成功、4 - 无订单
        if (item.data.order_status == 2) {
//            gotoShenhe(explainList);
            Map<String, String> map = new HashMap<>();
            map.put("type", Const.SendType.UPDATE_REPAY);
            EventBus.getDefault().post(new OnHomeEventMsg(map));
            ToastUtil.makeText(this, "支付成功").show();
            finish();
        } else if (item.data.order_status == 1) {
            ToastUtil.makeText(this, "支付失败").show();
        } else if (item.data.order_status == 4) {
            ToastUtil.makeText(this, "支付失败").show();
        } else if (item.data.order_status == 0) {
            if (item.data.is_alerts == 0) {
            } else if (item.data.is_alerts == 1) {
                Dialog.showConfirmDialog(this, new Dialog.DialogDefaultClickListener() {
                    //                确认支付成功
                    @Override
                    public void confirm() {
                        api.confirmDialog(item.data.notice_id, api.SUCCESS);
                    }

                    //                点击支付失败
                    @Override
                    public void cancel() {
                        api.confirmDialog(item.data.notice_id, api.FAILED);
//                        Dialog.showDefaultDialog(ShenHeActivity.this, "提示", "确定支付失败吗？", "确定", "返回", false, new Dialog.DialogDefaultClickListener() {
//                            @Override
//                            public void confirm() {
////                            点击返回，显示上一个Dialog;
//                                Dialog.showConfirmDialog(ShenHeActivity.this, new Dialog.DialogDefaultClickListener() {
//                                    @Override
//                                    public void confirm() {
//                                        api.confirmDialog(item.data.notice_id, api.SUCCESS);
//                                    }
//
//                                    @Override
//                                    public void cancel() {
//                                        Dialog.showDefaultDialog(ShenHeActivity.this, "提示", "确定支付失败吗？", "确定", "返回", false, new Dialog.DialogDefaultClickListener() {
//                                            @Override
//                                            public void confirm() {
//
//                                            }
//
//                                            @Override
//                                            public void cancel() {
//                                                api.confirmDialog(item.data.notice_id, api.FAILED);
//                                            }
//                                        });
//                                    }
//                                });
//                            }
//
//                            @Override
//                            public void cancel() {
//                                //                            点击确认，支付失败;
//                                api.confirmDialog(item.data.notice_id, api.FAILED);
//                            }
//                        });
                    }
                });
            }
        }
    }

    //取消订单
    public void getPaymentNoticeCancel(String notice_sn) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        PaymentNoticeCancelBean bean = new PaymentNoticeCancelBean();
        bean.notice_sn = notice_sn;
        Api.api_service.getPaymentNoticeCancel(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Util.startActivity(this, V3RepayMoneyActivity.class);
                    finish();
                });
    }

    @Override
    public void confirmDialogSuccess(ConfirmDilaogModel item, String confirm) {
//        if (confirm.equals(api.FAILED)) {
////            finish();
//        } else if (confirm.equals(api.SUCCESS)) {
//            
//        }
    }

    private boolean checkAliPayInstalled(Context context) {
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }

    @OnClick({R.id.btn_repay, R.id.btn_submit, R.id.btn_cancel_order})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_repay:
                if (data == null) {
                    api.getRestartPay(order);
                    return;
                }
//                "new_order": 1   //是否需要重新生成订单：0 - 否， 1 - 是
                if (data.data.new_order == 0) {
                    if (data.data.go_alipay == 1) {
                        isGotoPay = true;
                        if (!checkAliPayInstalled(this)) {
                            mWebView.loadUrl(data.data.alipay_money_links);
                            return;
                        }
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        Uri content_url = Uri.parse(Const.ALIPAY_START + data.data.alipay_money_links + Const.ALIPAY_END);
                        intent.setData(content_url);
                        startActivity(intent);
                    } else if (data.data.go_alipay == 0) {
                        mWebView.loadUrl(data.data.alipay_money_links);
                    }
                } else if (data.data.new_order == 1) {
                    Intent intent = new Intent(this, V3RepayMoneyActivity.class);
                    intent.putExtra("deal_id", dealId);
                    intent.putExtra("money", mMoney);
                    intent.putExtra("overdue", overdue);
                    intent.putExtra("total_money", totalMoney);
                    intent.putExtra("balance", balance);
                    startActivity(intent);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                    finish();
                }


                break;
            case R.id.btn_submit:
                finish();
                break;
            case R.id.btn_cancel_order:
                Dialog.showDefaultV3Dialog(this, "提醒", "该订单一旦取消\n将不可恢复，请慎重选择", "取消", "确定", new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {
                        getPaymentNoticeCancel(order);
                    }

                    @Override
                    public void cancel() {

                    }
                });
                break;
        }
    }
}
